package imageCreator;

import heightMap.HeightMap;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;

public class ImageCreator {

	// Returns a generated image.
	public void printImage(HeightMap map) {
		int size = map.getSize();
		double max = 0, min = 1000;
		int[][] grid = map.getMap();

		// Create a buffered image in which to draw
		BufferedImage bufferedImage = new BufferedImage(size, size,
				BufferedImage.TYPE_INT_RGB);

		// Create a graphics contents on the buffered image
		Graphics2D g2d = bufferedImage.createGraphics();

		// Draw graphics
		g2d.setColor(Color.white);
		g2d.fillRect(0, 0, size, size);

		// establish maxs, mins
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < size; j++) {
				if (grid[i][j] > max) {
					max = grid[i][j];
				}
				if (grid[i][j] <= min) {
					min = grid[i][j];
				}
			}
		}
		System.out.println("Max: " + max + "...Min: " + min);

		float redVal = 0.0f;
		double distance = max - min;
		System.out.println(distance);

		// draw individual squares to the graphics
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < size; j++) {
				// compare to min, scale
				// if (grid[i][j] < 0) {
				// blueVal = (256 * (grid[i][j] / min));
				// }
				// // compare to max, scale
				// else {
				// redVal = 256 * (grid[i][j] / max);
				// }

				// different scaling method
				redVal = (float) Math.abs(1 - ((grid[i][j] + distance) / (distance)));

				// adjust color values to stay in appropriate ranges
				if (redVal >= 1.0f) {
					redVal = 1.0f;
				}
				if (redVal <= 0) {
					redVal = 0.01f;
				}
				// set the color
				g2d.setColor(new Color(redVal, redVal, redVal));

				// reset defaults
				redVal = 1;

				// draw square
				g2d.fillRect(i - 1, j - 1, 3, 3);
			}
		}

		// Graphics context no longer needed so dispose it
		g2d.dispose();

		RenderedImage rendImage = bufferedImage;

		// Write generated image to a file
		try {
			// Save as PNG
			File file = new File("fault_method_height_map.png");
			ImageIO.write(rendImage, "png", file);
		} catch (IOException e) {
		}
	}
}
